'use strict';

const { Controller } = require('egg');
const { sign, verify } = require('jsonwebtoken');
/**
 * 1. 注册接口，没有的话，直接存入当前数据
 * 2. 同步信息接口（在保存作品的时候，同步当前作品信息到这个接口）
 * 3. 评论-针对已经发布作品进行协作评论。
 * 4. 添加协作人。
 * 5. 协作人查询接口（查人）
 * 6. 查作品
 * 7. 查评论
 *
 */

class HomeController extends Controller {
  async index() {
    const { ctx, app } = this;
    ctx.body = await app.mysql.get('users');
  }
  async refreshToken() {
    const { ctx, app } = this;
    try {
      const { refreshToken } = ctx.request.query;
      const token = refreshToken.split(' ')[1]
      const result = verify(token, app.config.jwt.secret)

      ctx.body = {
        code: 0,
        data: {
          token: 'Bearer '  + sign({
            phone: result.phone,
          }, app.config.jwt.secret, { expiresIn: 10 })
        }
      };
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }
  // 注册接口
  async register() {
    const { ctx, app } = this;
    try {
      const { phone } = ctx.request.body;
      const isUser = await app.mysql.get('users', { phone });
      if (!isUser) {
        // 插入数据
        await app.mysql.insert('users', { phone });
      }
      const secret = app.config.jwt.secret;
      const token = sign({ phone }, secret, { expiresIn: 10 });
      const refreshToken = sign({ phone }, secret);
      ctx.body = {
        code: 0,
        data: {
          token: `Bearer ${token}`,
          refreshToken: `Bearer ${refreshToken}`,
        },
      };
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }
  // 同步作品接口 post
  async syncLocalWork() {
    const { ctx, app } = this;
    try {
      const { workid, extra_json } = ctx.request.body;
      const isWork = await app.mysql.get('localWork', { workid });
      // 如果作品存在，就更新这个作品，如果作品不存在，就添加这个作品
      if (isWork) {
        console.log('isWork', isWork);
        // 作品存在
        const result = await app.mysql.update('localWork', {
          id: isWork.id,
          extra_json: JSON.stringify(extra_json),
        }); // 更新 posts 表中的记录
        ctx.body = {
          code: 1,
          data: result,
          msg: '作品更新成功',
        };
      } else {
        // 作品不存在
        const result = await this.app.mysql.insert('localWork', {
          workid,
          extra_json: JSON.stringify(extra_json),
        });
        ctx.body = {
          code: 1,
          data: result,
          msg: '作品同步成功',
        };
      }
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }
  // 添加评论接口
  async addComments() {
    const { ctx, app } = this;
    try {
      const { workid, creator, comment, previewImage } = ctx.request.body;
      const res = await app.mysql.get('localWork', { workid });
      // console.log('res:', res)

      if (res) {
        const result = await this.app.mysql.insert('comments', {
          localWorkId: res.id,
          creator,
          comment,
          previewImage,
        });
        ctx.body = {
          code: 1,
          data: result,
          msg: '评论添加成功',
        };
      } else {
        ctx.body = {
          code: -1,
          msg: '查找workid失败',
        };
      }
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }

  // 选中作品，然后添加协作人
  async addPartner() {
    const { ctx, app } = this;
    try {
      const { workid, partners } = ctx.request.body;
      const res = await app.mysql.get('localWork', { workid });
      console.log('res:', res);
      if (res) {
        const result = await this.app.mysql.update('localWork', {
          id: res.id,
          partners,
        });
        ctx.body = {
          code: 1,
          data: result,
          msg: '协作人添加成功',
        };
      } else {
        ctx.body = {
          code: -1,
          msg: '当前作品不存在',
        };
      }
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }

  // 协作人查询接口
  async getPartner() {
    const { ctx, app } = this;
    try {
      const { page = 1, size = 10 } = ctx.query;
      const results = await this.app.mysql.select('users');
      ctx.body = {
        code: 1,
        msg: '查询成功',
        data: results,
      };
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }

  // 查作品
  async getLocalWorkList() {
    const { ctx, app } = this;
    try {
      const { pageIndex = 0, pageSize = 5 } = ctx.query;
      const { phone } = ctx.state.user;
      console.log('page:', pageIndex, pageSize);
      const results = await app.mysql.query(
        `select * from localWork where partners like '%${phone}%' limit ? offset ?`,
        [pageSize * 1, pageIndex * 1 * pageSize]
      );
      const total = await app.mysql.query(
        `SELECT COUNT(*) as num FROM localWork where partners like '%${phone}%';`
      );

      ctx.body = {
        code: 1,
        msg: '查询成功',
        data: { total: total[0].num, results },
      };
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }
  // 查评论
  async getComments() {
    const { ctx, app } = this;
    try {
      const { workid } = ctx.query;
      if (workid) {
        const localWorkList = await app.mysql.get('localWork', { workid });
        console.log(localWorkList, 'localWorkList');
        const localWorkId = localWorkList.id;
        const results = await app.mysql.select('comments', {
          where: { localWorkId },
        });
        ctx.body = {
          code: 1,
          msg: '查询成功',
          data: { results },
        };
      } else {
        ctx.body = {
          code: -1,
          msg: '缺少参数wokid',
        };
      }
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }

  async getWorkById() {
    const { ctx, app } = this;
    try {
      const { workid } = ctx.query;
      const res = await app.mysql.get('localWork', { workid });
      if (res) {
        ctx.body = {
          code: 1,
          msg: '查询成功',
          data: res,
        };
      } else {
        ctx.body = {
          code: -1,
          msg: '当前作品不存在',
        };
      }
    } catch (error) {
      ctx.body = {
        code: -1,
        data: error,
      };
    }
  }
}

module.exports = HomeController;
